<template>
  <div>
    <el-container>
      <el-main>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>水果批发</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card class="box-card cardsy" shadow="always">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-input
                placeholder="请输入关键信息"
                v-model="querytext"
                class="input-with-select"
                @keyup.native.13="getShops()"
                @clear="getShops"
              >
              <!-- @change="getShops" -->
                <el-select v-model="select" slot="prepend" placeholder="请选择">
                  <el-option label="联系人" value="1"></el-option>
                  <el-option label="商铺编号" value="2"></el-option>
                  <el-option label="联系电话" value="3"></el-option>
                </el-select>
                <el-button slot="append" icon="el-icon-search" @click="getShops"
                  >搜索</el-button
                >
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-button
                type="primary"
                icon="el-icon-circle-plus-outline"
                @click="addShopDialog"
                >添加商铺</el-button
              ></el-col
            >
          </el-row>

          <template>
            <el-table :data="tableData" style="width: 100%" stripe border>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag type="info" effect="dark">售卖水果种类</el-tag>
                  <i class="el-icon-caret-right"></i>
                  <el-tag
                    effect="dark"
                    type="warning"
                    closable
                    v-for="tag in scope.row.fruitslist"
                    :key="tag.fruitName"
                    @close="handleClose(tag, scope.row)"
                  >
                    {{ tag.fruitName }}
                  </el-tag>
                  <el-input
                    id="input-new-tag"
                    v-if="inputVisible"
                    v-model="inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    id="button-new-tag"
                    size="small"
                    @click="showInput"
                    >+ 添加水果</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"> </el-table-column>
              <el-table-column prop="shopId" label="商铺编号" width="80">
              </el-table-column>
              <el-table-column prop="shopName" label="商铺名称" width="190">
              </el-table-column>
              <el-table-column prop="bossName" label="联系人" width="80">
              </el-table-column>
              <el-table-column prop="bossMobile" label="联系电话" width="120">
              </el-table-column>
              <el-table-column prop="shopAddress" label="商铺地址" width="150">
              </el-table-column>
              <el-table-column label="商铺状态" width="100">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.wordstatus"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="shopStateChanged(scope.row)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="修改商铺信息"
                    placement="top"
                  >
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      @click="editShopDialog(scope.row)"
                      >编辑</el-button
                    >
                  </el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除商铺"
                    placement="top"
                  >
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteShop(scope.row)"
                      >删除</el-button
                    >
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-card>

        <el-card class="cardsy">
          <el-row>
            <el-pagination
              background
              layout="prev, pager, next,total,sizes,jumper"
              :total="totalCount"
              :page-size="limit"
              :page-sizes="[3, 6, 9, 12, 15, 20, 30, 40, 50, 100]"
              :current-page="page"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              @prev-chick="handlePrev"
              @next-click="handleNext"
            >
            </el-pagination>
          </el-row>
        </el-card>

        <!-- 添加店铺dialog -->
        <el-dialog
          title="添加商铺"
          :visible.sync="addialogFormVisible"
          @close="addDialogClosed"
        >
          <el-form
            :model="shops"
            :rules="addFormRules"
            ref="addFormRef"
            label-width="100px"
          >
            <el-form-item label="店铺名称" prop="shopName">
              <el-input v-model="shops.shopName"></el-input>
            </el-form-item>
            <el-form-item label="店铺地址" prop="shopAddress">
              <el-input v-model="shops.shopAddress"></el-input>
            </el-form-item>
            <el-form-item label="联系人姓名" prop="bossName">
              <el-input v-model="shops.bossName"></el-input>
            </el-form-item>
            <el-form-item label="联系人电话" prop="bossMobile">
              <el-input v-model="shops.bossMobile"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addSubmit">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 修改店铺dialog -->
        <el-dialog
          title="修改商铺"
          :visible.sync="editdialogFormVisible"
          @close="editDialogClosed"
        >
          <el-form
            :model="editData"
            label-width="100px"
            ref="editFormRef"
            :rules="editFormRules"
          >
            <el-form-item label="店铺编号">
              <el-input v-model="editData.shopId" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="店铺名称" prop="shopName">
              <el-input v-model="editData.shopName"></el-input>
            </el-form-item>
            <el-form-item label="店铺地址" prop="shopAddress">
              <el-input v-model="editData.shopAddress"></el-input>
            </el-form-item>
            <el-form-item label="联系人姓名" prop="bossName">
              <el-input v-model="editData.bossName"></el-input>
            </el-form-item>
            <el-form-item label="联系人电话" prop="bossMobile">
              <el-input v-model="editData.bossMobile"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="editdialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="editSubmit">确 定</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>


<script>
export default {
  data() {
    var checkMobile = (rule, value, callback) => {
      let reg =
        /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的电话"));
      }
    };

    return {
      limit: 3,
      page: 1,
      totalCount: 0,
      inputVisible: false,
      inputValue: "",
      querytext: "",
      addialogFormVisible: false,
      editdialogFormVisible: false,
      select: "",
      tableData: [],
      editData: {},
      deleteData: {},
      shops: {
        shopId: 0,
        shopName: "",
        shopAddress: "",
        bossName: "",
        bossMobile: "",
        wordstatus: true,
        fruitslist: [],
      },
      addFormRules: {
        bossMobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        shopName: [
          { required: true, message: "请输入店铺名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        shopAddress: [
          { required: true, message: "请输入店铺地址", trigger: "blur" },
          {
            min: 5,
            max: 30,
            message: "长度在 5 到 30 个字符",
            trigger: "blur",
          },
        ],
        bossName: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" },
          { min: 3, max: 4, message: "长度在 3 到 4 个字符", trigger: "blur" },
        ],
      },
      editFormRules: {
        bossMobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        shopName: [
          { required: true, message: "请输入店铺名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        shopAddress: [
          { required: true, message: "请输入店铺地址", trigger: "blur" },
          {
            min: 5,
            max: 30,
            message: "长度在 5 到 30 个字符",
            trigger: "blur",
          },
        ],
        bossName: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" },
          { min: 3, max: 4, message: "长度在 3 到 4 个字符", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getShops();
  },
  methods: {
    getShops() {
      let url = `wholesalers?_page=${this.page}&_limit=${this.limit}`;
      if (this.querytext) {
        url = `wholesalers?_page=${this.page}&_limit=${this.limit}&q=${this.querytext}`;
      }
      this.$http.get(url).then((res) => {
        this.tableData = res.data;
        this.totalCount = parseInt(res.headers["x-total-count"]);
        // console.log(this.tableData);
      });
    },
    shopStateChanged(row) {
      //   console.log(row.id);
      this.$http.put(`wholesalers/` + row.id, row).then((rs) => {
        if (rs.status !== 200) {
          return this.$message.err("店铺状态更改失败");
        }
        this.$message.success("店铺状态更新成功");
      });
    },
    //添加店铺
    addShopDialog() {
      this.addialogFormVisible = true;
      this.$http.get("wholesalers?_sort=id").then((rs) => {
        this.shops.shopId = rs.data[rs.data.length - 1].id + 1;
      });
    },
    addSubmit() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return false;
        this.$http.post("wholesalers", this.shops).then((res) => {
          if (res.status !== 201) {
            this.$message.error("店铺添加失败...");
          } else {
            this.$message.success("店铺添加成功");
          }
          this.addialogFormVisible = false;
          this.getShops();
        });
      });
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //修改店铺
    editShopDialog(row) {
      this.editdialogFormVisible = true;
      this.editData = row;
    },
    editSubmit() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return false;
        this.$http
          .put(`wholesalers/${this.editData.id}`, this.editData)
          .then((res) => {
            if (res.status === 201) {
              this.$message.error("商铺修改失败...");
            } else {
              this.$message.success("商铺修改成功");
            }
            this.editdialogFormVisible = false;
            this.getShops();
          });
      });
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //删除店铺
    deleteShop(row) {
      this.$confirm("进行删除用户操作, 是否继续?", "删除用户", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete(`wholesalers/${row.id}`);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getShops();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          this.getShops();
        });
    },
    handleClose(tag, row) {
      row.fruitslist.splice(row.fruitslist.indexOf(tag), 1);
      this.$http.put(`wholesalers/${row.id}`, row).then((res) => {
        if (res.status === 201) {
          this.$message.error("水果删除失败...");
        } else {
          this.$message.success("水果删除成功");
        }
      });
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //添加水果
    handleInputConfirm(row) {
      let inputValue = this.inputValue;

      if (inputValue) {
        row.fruitslist.push({
          fruitName: inputValue,
          id: row.fruitslist.length + 101,
        });
      }
      this.inputVisible = false;
      this.inputValue = "";
      this.$http.put(`wholesalers/${row.id}`, row).then((res) => {
        if (res.status === 201) {
          this.$message.error("水果添加失败...");
        } else {
          this.$message.success("水果添加成功");
        }
      });
    },

     handleSizeChange(size) {
      this.limit = size;
      this.getShops();
      // this.$message("每页显示数量改变")
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getShops();
    },
    handlePrev(page) {
      this.page = page;
      this.getShops();
    },
    handleNext(page) {
      this.page = page;
      this.getShops();
    },
  },
};
</script>

<style>
.el-main {
  background-color: #e9eef3;
  color: #333;
}
.cardsy {
  margin: 15px 0px;
}
.el-table {
  margin-top: 20px;
}
.el-select .el-input {
  width: 130px;
}
.el-tag {
  margin: 10px;
}
#button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
#input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>